/**
 * \file serial.c
 * Serial communication code
 * 
 * Code for serial communication via USART0
 * 
 * AT91SAM7S-128 USB Mass Storage Device with SD Card by Michael Wolf\n
 * Copyright (C) 2008 Michael Wolf\n\n
 * 
 * This program is free software: you can redistribute it and/or modify\n
 * it under the terms of the GNU General Public License as published by\n
 * the Free Software Foundation, either version 3 of the License, or\n
 * any later version.\n\n
 * 
 * This program is distributed in the hope that it will be useful,\n
 * but WITHOUT ANY WARRANTY; without even the implied warranty of\n
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n
 * GNU General Public License for more details.\n\n
 * 
 * You should have received a copy of the GNU General Public License\n
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n
 * 
 */
 
#include "hardware_conf.h"
#include "firmware_conf.h"
#include "trace.h"
#include "serial.h"

/**
 * \var pUSART
 * Global Pointer to the debug channel usart 
 * 
*/
AT91S_DBGU * pUSART = AT91C_BASE_DBGU; 

/**
 * Init USART0
 * 
 * Init USART0.
 * Baudrate defined in hardware_conf.h
 * Parameters 8N1
 * 
 */
void usart0_init(void)
{
    *AT91C_PIOA_PDR =   AT91C_PA9_DRXD |        // Enable DRxD pin 
                        AT91C_PA10_DTXD;        // Enalbe DTxD pin 

    pUSART->DBGU_CR =   AT91C_US_RSTRX |        // Reset receiver
                        AT91C_US_RSTTX |        // Reset transmitter
                        AT91C_US_RXDIS |        // Receiver disable
                        AT91C_US_TXDIS;         // Transmitter disable

    pUSART->DBGU_MR =   AT91C_US_USMODE_NORMAL |    // Normal mode
                        AT91C_US_CLKS_CLOCK    |    // Clock = MCK
                        AT91C_US_CHRL_8_BITS   |    // 8-bit data
                        AT91C_US_PAR_NONE      |    // No parity
                        AT91C_US_NBSTOP_1_BIT;      // 1 Stop bit

    pUSART->DBGU_BRGR = BAUDRATE_DIV;       // Baudrate divisor

    pUSART->DBGU_CR =   AT91C_US_RXEN  |    // Receiver enable
                        AT91C_US_TXEN;      // Transmitter enable   
}

/**
 * Send character via USART0
 * 
 * \param   c   Character to send 
 * 
 */
void usart0_putchar(char c)
{
    while (!(pUSART->DBGU_CSR & AT91C_US_TXRDY));   // Wait for empty Tx buffer 
    pUSART->DBGU_THR = c;
}
